import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:syn_4s/core/constants/sp_key.dart';
import 'package:syn_4s/core/extension/build_context_extension.dart';
import 'package:syn_4s/core/extension/int_extension.dart';
import 'package:syn_4s/core/model/user_tag_model.dart';
import 'package:syn_4s/core/utils/sp_utils.dart';
import 'package:syn_4s/ui/widgets/gradient_button.dart';

import '../../../core/constants/tag_code.dart';
import '../../../core/router/router.dart';
import '../../../core/services/config.dart';
import '../../../core/services/login_request.dart';
import '../../../core/utils/toast_utils.dart';
import '../../../core/viewmodel/login_view_model.dart';
import '../../../generated/l10n.dart';
import '../../shared/app_theme.dart';
import '../../widgets/custom_ui.dart';

class LoginContent extends StatelessWidget {
  LoginViewModel vm = Get.find<LoginViewModel>();

  LoginContent({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        height: double.infinity,
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0xff0C558A), Color(0xff07233D)],
                begin: Alignment.centerLeft,
                end: Alignment.centerRight)),
        alignment: Alignment.center,
        padding: EdgeInsets.only(
            left: 12.px, right: 12.px, top: 80.px, bottom: 20.px),
        child: Column(
          children: [
            Expanded(
                child: SingleChildScrollView(
                    child: Column(
              children: buildColumnChildren(context),
            ))),
            buildForgetPw(context)
          ],
        ),
      ),
    );
  }

  List<Widget> buildColumnChildren(BuildContext context) {
    return [
      Image.asset(
        "assets/images/logo.png",
        width: 260.px,
        height: 40.px,
      ),
      SizedBox(
        height: 6.px,
      ),
      Text(
        "Smart Site Safety System (4S)",
        style: TextStyle(
            fontSize: 22.px, color: Colors.white, fontFamily: 'Oswald'),
      ),
      SizedBox(
        height: 32.px,
      ),
      Container(
        padding: EdgeInsets.only(
            left: 12.px, right: 12.px, top: 32.px, bottom: 6.px),
        decoration: BoxDecoration(
            color: AppTheme.loginContentColor,
            shape: BoxShape.rectangle,
            border: Border.all(color: AppTheme.orangeColor),
            boxShadow: [
              BoxShadow(color: AppTheme.orangeColor, blurRadius: 8.px)
            ]),
        child: Column(
          children: [
            buildTextField(S.of(context).username_hint, vm.userController,
                prefixIcon: "assets/images/person.png"),
            SizedBox(
              height: 16.px,
            ),
            Obx(() => buildTextField(S.of(context).pw_hint, vm.pwdController,
                obscureText: !vm.pwdVisible.value,
                suffixIcon: IconButton(
                  onPressed: () {
                    vm.pwdVisible.value = !vm.pwdVisible.value;
                  },
                  icon: Icon(
                    vm.pwdVisible.value
                        ? Icons.visibility
                        : Icons.visibility_off,
                    color: AppTheme.orangeColor,
                  ),
                ),
                prefixIcon: "assets/images/key.png")),
            buildButton(context),
            buildRemember(context),
          ],
        ),
      ),
    ];
  }

  void loginForm(BuildContext context) {
    if (vm.userController.text.isEmpty) {
      ToastUtils.showToast(S.of(context).p_username_hint);
      return;
    }
    if (vm.pwdController.text.isEmpty) {
      ToastUtils.showToast(S.of(context).p_pw_hint);
      return;
    }
    LoginRequest.login(vm.userController.text, vm.pwdController.text)
        .then((value) {
      if (value.status != HttpConfig.success) {
        ToastUtils.showToast(value.message ?? "");
        return;
      }
      SPUtils.set(
          keyPassword, vm.isRemember.value ? vm.pwdController.text : "");
      SPUtils.set(keyUser, value.data?.userInfo?.userName);
      SPUtils.set(keyEmail, value.data?.userInfo?.email);
      SPUtils.set(keyUserId, value.data?.userInfo?.id);
      SPUtils.set(keyToken, value.data?.token);
      SPUtils.set(keyRefreshToken, value.data?.refreshToken);
      SPUtils.set(keyProjId, value.data?.userInfo?.proj?.id);
      SPUtils.set(keyProjName, value.data?.userInfo?.proj?.name);
      SPUtils.set(keyProjCode, value.data?.userInfo?.proj?.code);
      List<UserTagModel> userTags = value.data?.tags ?? [];
      String codes = userTags
          .map((tag) => tag.code)
          .where((code) =>
              code != null &&
              code.isNotEmpty &&
              code != codeStatus &&
              code != codeRealLocation &&
              code != codeTowerCrane &&
              code != codeSurveillance)
          .join(',');
      print(codes);
      SPUtils.set(keyTagCode, codes);
      SPUtils.set(keyTag, jsonEncode(userTags.map((v) => v.toJson()).toList()));
      Get.offAndToNamed(MyRouter.mainRoute);
    }).catchError((err) {
      ToastUtils.showNetError(context);
    });
  }

  Widget buildTextField(String hintText, TextEditingController controller,
      {bool obscureText = false,
      Widget? suffixIcon,
      required String prefixIcon}) {
    return TextField(
        controller: controller,
        obscureText: obscureText,
        style: TextStyle(fontSize: 20.px),
        decoration: InputDecoration(
            contentPadding:
                EdgeInsets.symmetric(vertical: 12.px, horizontal: 10.px),
            filled: true,
            fillColor: Colors.white,
            hintText: hintText,
            enabledBorder: getWhiteOvalBorder(),
            focusedBorder: getFocusedBorder(),
            prefixIcon: ImageIcon(
              AssetImage(prefixIcon),
              color: AppTheme.orangeColor,
            ),
            suffixIcon: suffixIcon));
  }

  Widget buildButton(BuildContext context) {
    return GradientButton(
        margin: EdgeInsets.only(top: 32.px, bottom: 8.px),
        onPressed: () {
          loginForm(context);
        },
        child: Text(
          S.of(context).login,
          style: TextStyle(color: Colors.white, fontSize: 20.px),
        ));
  }

  Widget buildRemember(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 32.px,
          child: Obx(() => Checkbox(
              value: vm.isRemember.value,
              onChanged: (value) {
                vm.isRemember.value = !vm.isRemember.value;
                SPUtils.set(keyRememberPwd, vm.isRemember.value);
              },
              checkColor: Colors.white,
              fillColor:
                  WidgetStateProperty.resolveWith((Set<WidgetState> states) {
                if (states.contains(WidgetState.selected)) {
                  return AppTheme.orangeColor;
                }
                return Colors.white;
              }),
              side: WidgetStateBorderSide.resolveWith(
                (Set<WidgetState> states) {
                  return const BorderSide(
                      width: 1, color: AppTheme.orangeColor);
                },
              ))),
        ),
        GestureDetector(
            onTap: () {
              vm.isRemember.value = !vm.isRemember.value;
              SPUtils.set(keyRememberPwd, vm.isRemember.value);
            },
            child: Text(context.l10n.remember_pwd))
      ],
    );
  }

  Widget buildForgetPw(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (vm.userController.text.isEmpty) {
          ToastUtils.showToast(context.l10n.p_username_hint);
          return;
        }
        Get.toNamed(MyRouter.forgotPwRoute);
      },
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset("assets/images/lock.png"),
          SizedBox(
            width: 8.px,
          ),
          Text(
            S.of(context).forgot_pw,
            style: const TextStyle(color: AppTheme.orangeColor),
          )
        ],
      ),
    );
  }
}
